package com.taoyige.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.sina.weibo.sdk.openapi.models.ErrorInfo;
import com.taoyige.AppConfig;
import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.api.ApiClient;
import com.taoyige.bean.AccessInfo;
import com.taoyige.bean.User;
import com.taoyige.common.UIHelper;
import com.taoyige.widget.LoadingDialog;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendAuth;
import com.tencent.mm.sdk.openapi.SendAuth.Resp;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

/**
 * 用户登陆
 * 
 * @author peter
 * @version 1.0
 * @date 2014-11-20
 */
public class UserLoginActivity extends BaseActivity  {

	private AppContext appContext;
	private Handler handler;
	private LoadingDialog loading;

	private User user;

	private int loginType;

	private Tencent mTencent;
	private UserInfo userInfo;
	private WeiboAuth mWeiboAuth;
	private Oauth2AccessToken accessToken;
	private SsoHandler mSsoHandler;
	private UsersAPI mUsersAPI;

	private ImageButton user_qq_login;
	private ImageButton user_weibo_login;

	private ImageButton user_signin_wechat;
	
	private static final String SCOPE = "all";

	private ImageButton returnBack;
	private ImageButton homePage;
	private TextView userHeadText;
	private  IWXAPI wxAPI;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_signin_main);
		appContext = (AppContext) getApplication();
		if (mTencent == null)
			mTencent = Tencent.createInstance(AppConfig.APP_KEY_QQ, this);
		
		mWeiboAuth = new WeiboAuth(this, AppConfig.APP_KEY_WEIBO, AppConfig.WEIBO_REDIRECT_URL, AppConfig.SCOPE_WEIBO);
		
		if(wxAPI==null){
			wxAPI= WXAPIFactory.createWXAPI(this, AppConfig.APP_KEY_WECHAT, false);
		}
		wxAPI.registerApp(AppConfig.APP_KEY_WECHAT);
		
		loginType = getIntent().getIntExtra(AppConfig.LOGIN_TYPE, 0);
		this.initView();
	}

	private void initView() {
		returnBack=(ImageButton)findViewById(R.id.user_hear_return_back);
		homePage=(ImageButton)findViewById(R.id.user_hear_homePage);
		userHeadText=(TextView)findViewById(R.id.user_hear_text);
		userHeadText.setText("用户登录");
		
		returnBack.setOnClickListener(homeListener);
		homePage.setOnClickListener(homeListener);
		
		user_qq_login = (ImageButton) findViewById(R.id.user_signin_qq);
		user_qq_login.setOnClickListener(qqLoginClickListener);
		user_weibo_login = (ImageButton) findViewById(R.id.user_signin_weibo);
		user_weibo_login.setOnClickListener(wechatLoginClickListener);
		
		user_signin_wechat=(ImageButton) findViewById(R.id.user_signin_wechat);
		user_signin_wechat.setOnClickListener(wechatLoginClickListener);
	}
	
	public View.OnClickListener homeListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			UIHelper.showHomePage(v.getContext());
		}
	};

	private View.OnClickListener weiboLoginClickListener = new View.OnClickListener() {
		public void onClick(View v) {

			// 判断之前是否登陆过

			/*
			 * AccessInfo weiboObj = AppConfig.readAccessToken(
			 * UserLoginActivity.this, AppConfig.LOGIN_OAUTH_WEIBO); if
			 * (weiboObj != null && weiboObj.getUid() != null) { mAccessToken =
			 * new Oauth2AccessToken(); mAccessToken.setUid(weiboObj.getUid());
			 * mAccessToken.setToken(weiboObj.getAccessToken());
			 * mAccessToken.setExpiresTime(weiboObj.getExpiresTime()); }
			 * weiboHelper.progressDialog = new
			 * LoadingDialog(UserLoginActivity.this);
			 * weiboHelper.progressDialog.
			 * setLoadText(UserLoginActivity.this.getString(R.string.logining));
			 * weiboHelper.progressDialog.show(); if (mAccessToken != null) {
			 * 
			 * weiboHelper.setAccessToken(mAccessToken);
			 * weiboHelper.getUserInfo(); } else { weiboHelper.authorize(); }
			 */
			AccessInfo ac = AppConfig.readAccessToken(UserLoginActivity.this,
					AppConfig.LOGIN_OAUTH_WEIBO);
			accessToken = new Oauth2AccessToken();
			accessToken.setUid(ac.getUid());
			accessToken.setToken(ac.getAccessToken());
			accessToken.setExpiresTime(ac.getExpiresTime());
			if (ac.getExpiresTime()>System.currentTimeMillis()&&accessToken.isSessionValid()) {
				mUsersAPI = new UsersAPI(accessToken);
				initUserInfo(AppConfig.LOGIN_OAUTH_WEIBO);
			}else{
				 mSsoHandler = new SsoHandler(UserLoginActivity.this, mWeiboAuth);
				 mSsoHandler.authorize(new AuthListener());
			}

		}
	};

	private View.OnClickListener qqLoginClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			AccessInfo ac = AppConfig.readAccessToken(UserLoginActivity.this,AppConfig.LOGIN_OAUTH_QQ);
			mTencent.setAccessToken(ac.getAccessToken(), ac.getExpiresIn()+"");
			mTencent.setOpenId(ac.getUid());
			if (ac.getExpiresTime()<System.currentTimeMillis()||!mTencent.isSessionValid()) {
				mTencent.login(UserLoginActivity.this, SCOPE, qqLoginListener);
			} else {
				initUserInfo(AppConfig.LOGIN_OAUTH_QQ);
			}
		}
	};

	private View.OnClickListener wechatLoginClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			
			// 检查是否安装微信

		    if(!wxAPI.isWXAppInstalled()) {
		    	UIHelper.ToastMessage(UserLoginActivity.this, "抱歉，您尚未安装微信客户端或者微信客户端没有登录！");
		    	return;
		    }
		    // 检查是否支持

		    if(wxAPI.getWXAppSupportAPI() < AppConfig.WX_MIN_SUPPORTED_VERSION) {
		    	UIHelper.ToastMessage(UserLoginActivity.this, "抱歉，您的微信版本不支持微信登录！");
		    	return;
		    }
		    
		    
			final SendAuth.Req req = new SendAuth.Req();
			req.scope = "snsapi_userinfo";
			req.state = "taoyige";
			wxAPI.sendReq(req);
			//initUserInfo(AppConfig.LOGIN_OAUTH_WECHAT);

		}
	};
	
	private void initUserInfo(int oauth_type) {
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (loading != null)
					loading.dismiss();
				if (msg.what == AppConfig.OAUTH_AccessToken_ACCESS
						&& msg.obj != null) {
					user = (User) msg.obj;
					if (user != null) {
						ApiClient.cleanCookie();

						if (loginType == AppConfig.LOGIN_TYPE_USER_AVATAR_BUTTON) {
							UIHelper.showUserCenter(UserLoginActivity.this,AppConfig.BADGE_NO);

						} else if (loginType == AppConfig.LOGIN_TYPE_USER_INDEX_BUY_BUTTON) {
							// 跳转到首页

						} else if (loginType == AppConfig.LOGIN_TYPE_USER_AVATAR_BUTTON) {
							// 跳转到详情页面

						} else {
							// 跳转到用户中心

						}
					}

				} else if (msg.obj != null) {
					UIHelper.ToastMessage(UserLoginActivity.this, msg.obj + "");
				}
			}
		};

		switch (oauth_type) {

		case AppConfig.LOGIN_OAUTH_QQ:
			this.loadQQUserInfoThread();
			break;
		case AppConfig.LOGIN_OAUTH_WEIBO:
			this.loadWeiboUserInfoThread();
			break;
		}
	}

	IUiListener qqLoginListener = new BaseUiListener() {
		@Override
		protected void doComplete(JSONObject values) {
			initQQOpenidAndToken(values);
			initUserInfo(AppConfig.LOGIN_OAUTH_QQ);
		}
	};

	public void initQQOpenidAndToken(JSONObject jsonObject) {
		try {
			String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
			String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
			String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
			if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
					&& !TextUtils.isEmpty(openId)) {
				mTencent.setAccessToken(token, expires);
				mTencent.setOpenId(openId);
				// 保存 Token 到 SharedPreferences

				AccessInfo ac = new AccessInfo();
				ac.setUid(openId);
				ac.setAccessToken(token);
				ac.setExpiresIn(Long.parseLong(expires));
				ac.setExpiresTime(Long.parseLong(expires));
				AppConfig.writeAccessToken(UserLoginActivity.this,
						AppConfig.LOGIN_OAUTH_QQ, ac);
			}
			user = new User();
			user.setId(AppConfig.LOGIN_OAUTH_QQ + "-" + openId);
		} catch (Exception e) {
		}
	}

	private void loadQQUserInfoThread() {
		loading = new LoadingDialog(this);
		loading.setLoadText(UserLoginActivity.this.getString(R.string.logining));
		loading.show();
		if (mTencent != null && mTencent.isSessionValid()) {
			final IUiListener listener = new IUiListener() {
				@Override
				public void onError(UiError e) {
				}

				@Override
				public void onComplete(final Object response) {
					new Thread() {
						@Override
						public void run() {
							JSONObject json = (JSONObject) response;
							Message msg = new Message();
							AccessInfo ac = AppConfig.readAccessToken(
									UserLoginActivity.this,
									AppConfig.LOGIN_OAUTH_QQ);
							if (user == null) {
								user = new User();
							}
							user.setId(AppConfig.LOGIN_OAUTH_QQ + "-"
									+ ac.getUid());
							user.setPid(AppConfig.LOGIN_OAUTH_QQ);
							user.setpUserID(ac.getUid());
							try {
								if (json.has("nickname")) {
									user.setpUserName(json.getString("nickname"));
									user.setUserName(json.getString("nickname"));
								}
								if (json.has("figureurl"))
									user.setThumbUrl(json.getString("figureurl_qq_2"));

								appContext.saveLoginInfo(user);

								msg.obj = user;
								msg.what = AppConfig.OAUTH_AccessToken_ACCESS;
							} catch (JSONException e) {
								msg.what = AppConfig.OAUTH_AccessToken_ERROR;
								msg.obj = e;
							}
							handler.sendMessage(msg);
						}
					}.start();
				}

				@Override
				public void onCancel() {
				}
			};
			userInfo = new UserInfo(appContext, mTencent.getQQToken());
			userInfo.getUserInfo(listener);
		}
	}

	/** QQ OAuth Start */
	private class BaseUiListener implements IUiListener {

		@Override
		public void onComplete(Object response) {
			if (null == response) {
				UIHelper.ToastMessage(UserLoginActivity.this,
						UserLoginActivity.this
								.getString(R.string.OAUTH_AccessToken_ERROR));
				return;
			}
			JSONObject jsonResponse = (JSONObject) response;
			if (null != jsonResponse && jsonResponse.length() == 0) {
				UIHelper.ToastMessage(UserLoginActivity.this,
						UserLoginActivity.this
								.getString(R.string.OAUTH_AccessToken_ERROR));
				return;
			}
			UIHelper.ToastMessage(UserLoginActivity.this,
					UserLoginActivity.this
							.getString(R.string.OAUTH_AccessToken_ACCESS));
			doComplete((JSONObject) response);
		}

		protected void doComplete(JSONObject values) {

		}

		@Override
		public void onError(UiError e) {

			UIHelper.ToastMessage(UserLoginActivity.this, "onError: "
					+ e.errorDetail);
		}

		@Override
		public void onCancel() {
			UIHelper.ToastMessage(UserLoginActivity.this, "取消授权登陆");
		}
	}

	/** QQ OAuth End */

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.onDestroy();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// SSO 授权回调

		// 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResult


		if (mSsoHandler != null)
			mSsoHandler.authorizeCallBack(requestCode, resultCode,data);


		if (mTencent != null)
			mTencent.onActivityResult(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);

	}
	
class AuthListener implements WeiboAuthListener {
        
        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token

            accessToken = Oauth2AccessToken.parseAccessToken(values);
            if (accessToken.isSessionValid()) {
                
            	AccessInfo ac=new AccessInfo();
            	ac.setUid(accessToken.getUid());
            	ac.setAccessToken(accessToken.getToken());
            	ac.setExpiresIn(accessToken.getExpiresTime());
            	ac.setExpiresTime(accessToken.getExpiresTime());

                // 保存 Token 到 SharedPreferences

                AppConfig.writeAccessToken(UserLoginActivity.this, AppConfig.LOGIN_OAUTH_WEIBO,ac);
                
                mUsersAPI = new UsersAPI(accessToken);
                
                initUserInfo(AppConfig.LOGIN_OAUTH_WEIBO);
               
            } else {
                String code = values.getString("code");
                String message = "微博登陆失败，原因是：";
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                Toast.makeText(UserLoginActivity.this, message, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancel() {
           UIHelper.ToastMessage(UserLoginActivity.this, "登陆取消");
        }

        @Override
        public void onWeiboException(WeiboException e) {
        	 UIHelper.ToastMessage(UserLoginActivity.this, "Auth exception : " + e.getMessage());
        }
    }
	

private void loadWeiboUserInfoThread() {
	loading = new LoadingDialog(this);
	loading.setLoadText(UserLoginActivity.this.getString(R.string.logining));
	loading.show();
	if (mWeiboAuth != null && accessToken.isSessionValid()) {
		 long uid = Long.parseLong(accessToken.getUid());
		    mUsersAPI.show(uid, mListener);
	}
}


/**
 * 微博 OpenAPI 回调接口。
 */
private RequestListener mListener = new RequestListener() {
    @Override
    public void onComplete(final String response) {
        if (!TextUtils.isEmpty(response)) {
        	new Thread(){
				@Override
				public void run() {
			            if (!TextUtils.isEmpty(response)) {
			                // 调用 User#parse 将JSON串解析成User对象

							User user=new User();
							Message msg = new Message();
			            	com.sina.weibo.sdk.openapi.models.User weiboUser = com.sina.weibo.sdk.openapi.models.User.parse(response);
			                if (weiboUser != null) {
			                	
			                	user.setpUserName(weiboUser.screen_name);
			                    user.setUserName(weiboUser.screen_name);
			                    
			                    user.setPid(AppConfig.LOGIN_OAUTH_WEIBO);
			                    user.setpUserID(weiboUser.id);
			                    user.setThumbUrl(weiboUser.avatar_large);
			                    user.setId(user.getPid()+"-"+user.getpUserID());
			                    
			                    appContext.saveLoginInfo(user);
			                    		
			                    //TODO 更新用户API

			                    msg.obj = user;
								msg.what =  AppConfig.OAUTH_AccessToken_ACCESS;
								
			                } else {
			                    msg.what =  AppConfig.OAUTH_ERROR;	
								msg.obj = null;
			                }
						handler.sendMessage(msg);
					}
				}
			}.start();
            } else {
                Toast.makeText(UserLoginActivity.this, response, Toast.LENGTH_LONG).show();
            }
        }

    @Override
    public void onWeiboException(WeiboException e) {
        ErrorInfo info = ErrorInfo.parse(e.getMessage());
        Toast.makeText(UserLoginActivity.this, info.toString(), Toast.LENGTH_LONG).show();
    }
};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}


}